package com.brillilab.service.logic.kit;

import com.brillilab.common.entity.PageVo;
import com.brillilab.common.utils.MyBeanUtils;
import com.brillilab.domain.enums.kit.KitUsageEnum;
import com.brillilab.domain.po.inventory.ReagentInventory;
import com.brillilab.domain.po.kit.Kit;
import com.brillilab.domain.po.kit.KitRegularUsage;
import com.brillilab.domain.po.kit.KitRegularUsageGroup;
import com.brillilab.domain.po.kit.KitUsage;
import com.brillilab.domain.vo.kit.KitRegularUsageList;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.core.inventory.IReagentInventoryService;
import com.brillilab.service.core.kit.IKitRegularUsageService;
import com.brillilab.service.core.kit.IKitService;
import com.brillilab.service.core.kit.IKitUsageService;
import com.brillilab.service.core.kit.IkitRegularUsageGroupService;
import com.brillilab.service.core.system.IDictService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 常用清单
 */
@Service
@Transactional
public class KitRegularUsageLogic {

    @Autowired
    private IKitRegularUsageService kitRegularUsageService;
    @Autowired
    private IKitUsageService kitUsageService;
    @Autowired
    private IkitRegularUsageGroupService kitRegularUsageGroupService;
    @Autowired
    private IReagentInventoryService reagentInventoryService;
    @Autowired
    private IKitService kitService;
    @Autowired
    private IDictService dictService;

    /**
     * 保存取用清单为常用
     *
     * @param usageTimeStr
     */
    public void addUsageToRegularList(UserInfoVo userInfo,String usageTimeStr) {

        Assert.isTrue(userInfo!=null && StringUtils.isNotBlank(usageTimeStr),"参数缺失！");

        Date usageTime=new Date(Long.valueOf(usageTimeStr.trim()));

        List<KitRegularUsage> kitRegularUsages=kitRegularUsageService.selectList(userInfo.getLabId(),userInfo.getLabMemberId(),usageTime);

        Assert.isTrue(CollectionUtils.isEmpty(kitRegularUsages),"常用清单已存在，无法重复添加！");


        List<KitUsage> kitUsages=kitUsageService.selectList(userInfo.getLabId(),
                userInfo.getLabMemberId(),usageTime,KitUsageEnum.State.RETURNED.getValue(),KitUsageEnum.State.NOT_RETURN.getValue());
        //常用清单组
        KitRegularUsageGroup group=new KitRegularUsageGroup();
        group.setName("常用清单" + usageTime.getTime());
        group.setLabId(userInfo.getLabId());
        group.setLabMemberId(userInfo.getLabMemberId());
        boolean rs=kitRegularUsageGroupService.insert(group);
        Assert.isTrue(rs,"业务操作失败！");
        kitUsages.forEach(kitUsage -> {
            //常用清单 关联组ID
            KitRegularUsage kitRegularUsage=MyBeanUtils.copyBean(kitUsage,KitRegularUsage.class);
            kitRegularUsage.setGroupId(group.getId());
            kitRegularUsage.setCreateTime(null);
            kitRegularUsage.setUpdateTime(null);
            boolean rs1=kitRegularUsageService.insert(kitRegularUsage);
            Assert.isTrue(rs1,"业务操作失败！");
        });
    }

    /**
     * 常用清单列表
     *
     * @param labId
     * @param labMemberId
     * @return
     */
    public PageVo<KitRegularUsageList> getRegularUsageList(Long labId,Long labMemberId,Integer pageNum,Integer pageSize) {

        Assert.isTrue(labId != null && labMemberId != null && pageNum != null && pageSize != null,"参数缺失！");

        Map<Integer, String> unitMap=dictService.getUnitMap();

        PageHelper.startPage(pageNum,pageSize);
        //常用清单组
        List<KitRegularUsageGroup> groups=kitRegularUsageGroupService.selectList(labId,labMemberId);

        //一次性查询出kitRegularUsage再筛选
        List<Long> groupIds=groups.stream().map(KitRegularUsageGroup::getId).collect(Collectors.toList());
        List<KitRegularUsage> kitRegularUsagesAll=kitRegularUsageService.selectList(groupIds);

        //一次性查询出reagentInventory再筛选
        Set<Long> inventoryIds=kitRegularUsagesAll.stream().map(KitRegularUsage::getInventoryId).collect(Collectors.toSet());
        List<ReagentInventory> reagentInventorys=reagentInventoryService.selectList(new ArrayList<Long>(inventoryIds),null);

        PageVo<KitRegularUsageGroup> kitRegularUsageGroupPageVo=new PageVo<>(groups);
        //返回的清单组信息
        List<KitRegularUsageList> kitRegularUsageLists=new ArrayList<>();
        if(!CollectionUtils.isEmpty(groups)){
            groups.forEach(group -> {
                //清单项
                List<KitRegularUsage> kitRegularUsages=kitRegularUsagesAll.stream().filter(e -> e.getGroupId().equals(group.getId())).collect(Collectors.toList());
                //unit
                kitRegularUsages.forEach(kitRegularUsage -> {
                    ReagentInventory reagentInventory=reagentInventorys.stream().filter(e -> e.getId().equals(kitRegularUsage.getInventoryId())).findFirst().orElse(null);
                    String unit=unitMap.get(reagentInventory.getUnit());
                    kitRegularUsage.setUnit(unit);
                });
                List<KitRegularUsage> collect=kitRegularUsages.stream().sorted((e1,e2) -> e1.getId() > e2.getId() ? 1 : -1).collect(Collectors.toList());
                KitRegularUsageList kitRegularUsageList=new KitRegularUsageList();
                kitRegularUsageList.setName(group.getName());
                kitRegularUsageList.setGroupId(group.getId());
                kitRegularUsageList.setItems(collect);
                kitRegularUsageLists.add(kitRegularUsageList);
            });
        }

        PageVo<KitRegularUsageList> rs=new PageVo<>();
        rs.setStartRow(kitRegularUsageGroupPageVo.getStartRow());
        rs.setTotalRow(kitRegularUsageGroupPageVo.getTotalRow());
        rs.setTotalPage(kitRegularUsageGroupPageVo.getTotalPage());
        rs.setPageSize(kitRegularUsageGroupPageVo.getPageSize());
        rs.setPageNum(kitRegularUsageGroupPageVo.getPageNum());
        rs.setHasNext(kitRegularUsageGroupPageVo.isHasNext());
        rs.setHasPrevious(kitRegularUsageGroupPageVo.isHasPrevious());
        rs.setContent(kitRegularUsageLists);

        return rs;
    }

    /**
     * 常用清单再次取用
     *
     * @param groupId
     */
    public void takeAgain(Long groupId,Long labId,Long labMemberId) {

        Assert.isTrue(groupId != null && labId != null && labMemberId != null,"参数缺失！");

        KitRegularUsageGroup group=kitRegularUsageGroupService.selectOne(groupId,labId,labMemberId);
        Assert.notNull(group,"常用清单不存在！");

        List<KitRegularUsage> kitRegularUsages=kitRegularUsageService.selectList(groupId);
        List<KitUsage> exists=kitUsageService.selectList(labId,labMemberId,KitUsageEnum.State.TAKE.getValue());

        //一次性查询出reagentInventory再筛选
        Set<Long> inventoryIds=kitRegularUsages.stream().map(KitRegularUsage::getInventoryId).collect(Collectors.toSet());
        List<ReagentInventory> reagentInventorys=reagentInventoryService.selectList(new ArrayList<Long>(inventoryIds),null);

        List<KitUsage> kitUsages=new ArrayList<>();
        List<KitUsage> kitUsageUpdates=new ArrayList<>();
        Date updateTime=new Date();
        kitRegularUsages.forEach(kitRegularUsage -> {
            ReagentInventory reagentInventory=reagentInventorys.stream().filter(e -> e.getId().equals(kitRegularUsage.getInventoryId())).findFirst().orElse(null);
            BigDecimal amount=kitRegularUsage.getTakeAmount();

            KitUsage kitUsage=null;
            Optional<KitUsage> first=exists.stream().filter(e -> e.getInventoryId().equals(reagentInventory.getId())).findFirst();
            if(reagentInventory != null){
                //takeAmount值大于可用值，设置可用值
                amount=amount.compareTo(reagentInventory.getAmount()) > 0 ? reagentInventory.getAmount() : amount;
                //判断Kit是否存在
                Kit kit=kitService.selectById(reagentInventory.getKitId());
                Assert.notNull(kit,"试剂不存在！");
                //设置其他参数
                if(!first.isPresent()){
                    kitUsage=MyBeanUtils.copyBean(kitRegularUsage,KitUsage.class);
                    kitUsage.setId(null);
                    kitUsage.setTakeAmount(amount);
                    kitUsage.setRegularUsageGroupId(groupId);
                    kitUsage.setState(KitUsageEnum.State.TAKE.getValue());
                    kitUsage.setUsageTime(null);
                    kitUsage.setCreateTime(null);
                    kitUsage.setUpdateTime(null);
                    kitUsages.add(kitUsage);
                }else{
                    kitUsage=first.get();
                    kitUsage.setTakeAmount(kitUsage.getTakeAmount().add(amount));
                    kitUsage.setUpdateTime(updateTime);
                    kitUsageUpdates.add(kitUsage);
                }
            } else {
                //TODO 成分没有入库处理
            }
        });
        if(kitUsages.size() > 0){
            Integer rs=kitUsageService.insertBatch(kitUsages);
            Assert.isTrue(rs == kitUsages.size(),"操作失败！");
        }
        if(kitUsageUpdates.size() > 0){
            Integer rs2=kitUsageService.updateBatch(kitUsageUpdates);
            Assert.isTrue(rs2 == kitUsageUpdates.size(),"操作失败！");
        }
    }

    /**
     * 删除常用清单
     *
     * @param groupId
     */
    public void deleteRegularUsage(Long labId,Long labMemberId,Long groupId) {

        Assert.isTrue(groupId!=null && labId!=null && labMemberId!=null,"参数缺失！");

        KitRegularUsageGroup group=kitRegularUsageGroupService.selectOne(groupId,labId,labMemberId);
        Assert.notNull(group,"常用清单不存在！");
        List<KitRegularUsage> kitRegularUsages=kitRegularUsageService.selectList(groupId);
        List<Long> ids=kitRegularUsages.stream().map(KitRegularUsage::getId).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(ids)){
            kitRegularUsageService.deleteBatch(ids);
        }
        boolean b=kitRegularUsageGroupService.deleteById(groupId);
        Assert.isTrue(b,"业务操作失败！");
    }

    /**
     * 修改常用清单名称
     *
     * @param groupId
     * @param name
     * @return
     */
    public KitRegularUsageGroup renameRegularUsage(Long labId,Long labMemberId,Long groupId,String name) {

        Assert.isTrue(labId!=null && labMemberId!=null && groupId != null && StringUtils.isNotBlank(name),"参数缺失！");

        KitRegularUsageGroup group=kitRegularUsageGroupService.selectOne(groupId,labId,labMemberId);
        Assert.notNull(group,"常用清单不存在！");
        group.setName(name);
        boolean rs=kitRegularUsageGroupService.updateById(group);
        Assert.isTrue(rs,"业务操作失败！");
        return group;
    }
}
